package cn._2dland.bots.servlets;

import java.io.IOException;
import java.util.TimeZone;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn._2dland.bots.jdo.U115AccountManager;
import cn._2dland.bots.jdo.models.U115Account;

@SuppressWarnings("serial")
public class BotManager extends HttpServlet {
	public static final int ACTION_CREATE = 1;
	public static final int ACTION_DELETE = 2;
	public static final int ACTION_UPDATEPASSWORD = 3;
	public static final int ACTION_UPDATESTATUS = 4;

	public void init() throws ServletException {
		super.init();
		TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String act = req.getParameter("action");
		String aid = req.getParameter("aid");
		String user = req.getParameter("user");
		String pass = req.getParameter("pass");
		String st = req.getParameter("status");

		String result = null;
		try{
			if(act == null)
				throw new IllegalArgumentException("invalid action");
			int action = Integer.parseInt(act);
			Long accountID = aid==null ? null : Long.valueOf(aid);
			int status = st==null ? -1 : Integer.parseInt(st);

			switch(action){
			case ACTION_CREATE:
				if(user == null || pass == null)
					throw new IllegalArgumentException("invalid account information");
				U115Account acct = U115AccountManager.create(user, pass);
				if(acct == null)
					throw new Exception("create account failed");
				accountID = acct.getID();
				break;
			case ACTION_DELETE:
				if(accountID == null)
					throw new IllegalArgumentException("invalid account information");
				if(!U115AccountManager.remove(accountID))
					throw new Exception("remove failed");
				break;
			case ACTION_UPDATEPASSWORD:
				if(pass != null){
					if(accountID == null)
						throw new IllegalArgumentException("invalid account information");
					/*if(!U115AccountManager.updatePassword(accountID, pass))
						throw new Exception("update failed");*/
				}
				break;
			case ACTION_UPDATESTATUS:
				if(status >= 0){
					if(accountID == null)
						throw new IllegalArgumentException("invalid account information");
					if(!U115AccountManager.setStatus(accountID, status))
						throw new Exception("update failed");
				}
				break;
			}
			result = "{\"ok\":1, \"aid\":" + accountID + "}";
		}
		catch (Exception e) {
			result = "{\"ok\":0}";
			e.printStackTrace();
		}
		resp.setContentLength(result.length());
		resp.getWriter().print(result);
	}
}